package day3.datasource;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.logging.Logger;

import javax.sql.DataSource;

public class MyDataSource2 implements DataSource {
	private LinkedList<Connection> list=new LinkedList<Connection>();
	private static final String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
	private static final String user="root";
	private static final String password="root";
	private int min=5;
	private int max=10;
	private int current=0;
	
	public MyDataSource2() throws SQLException{
		for(int i=0;i<5;i++){
			list.addLast(createConnection());
		}
		System.out.println("in database construct list size() =: "+list.size());
		for(int i=0;i<5;i++){
			System.out.println(list.get(i));
		}
	}
	
	public Connection getConnection()
			throws SQLException {
		// TODO Auto-generated method stub
		Connection connection=null;
		current++;
		if(current>max){
			current--;
			throw new RuntimeException("链接全部用完，没有链接可用");
		}else {
			if(list.size()>0){
				connection=list.remove(0);
				System.out.println("in datasource connection is ="+connection);
				return connection;
			}else {
				System.out.println("list size() is 0");
				return createConnection();
			}
		}
	}
	
	public int reduceCurrent(){
		return --current;
	}
	
	private Connection createConnection() throws SQLException{
		Connection connection=DriverManager.getConnection(url, user, password);
		return new MyConnetionHandler(this).bind(connection);
	}
	
	public void back2Pool(Connection connection){
		list.addLast(connection);
	}
	

	public PrintWriter getLogWriter() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	public void setLogWriter(PrintWriter out) throws SQLException {
		// TODO Auto-generated method stub

	}

	public void setLoginTimeout(int seconds) throws SQLException {
		// TODO Auto-generated method stub

	}

	public int getLoginTimeout() throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}

	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		// TODO Auto-generated method stub
		return null;
	}

	public <T> T unwrap(Class<T> iface) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	public Connection getConnection(String username, String password)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}


	


}
